/**
 * 
 */
package com.txby.pf.modules.job.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.SecurityUtils;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jck.mybatis.mapper.MybatisBaseDaoCRUD;
import com.jck.tools.ChkUtil;
import com.txby.pf.common.utils.Constant;
import com.txby.pf.common.utils.Constant.ScheduleStatus;
import com.txby.pf.modules.job.utils.StationNotesUtils;
import com.txby.pf.modules.sys.entity.SysUserEntity;
import com.txby.pf.modules.sys.service.SysDeptService;
import com.txby.platformCore.entity.ProductDeviceInit;
import com.txby.platformCore.entity.StationNotes;

/**
 * @author Administrator
 *
 */
@Service
public class StationNotesJobService extends MybatisBaseDaoCRUD <StationNotes>{
	@Autowired
    private Scheduler scheduler;
	@Autowired
	private SysDeptService sysDeptService;
	
	 
	
	/**
	 * 项目启动时，初始化定时器
	 */
	@PostConstruct
	public void init(){
		List<StationNotes> scheduleJobList = this.findAll("select * from "+tableName(StationNotes.class)+"", StationNotes.class, null);
		if(ChkUtil.isEmptyAllObject(scheduleJobList)){
			System.out.println("没有任务提醒设置");
			scheduleJobList=new ArrayList<StationNotes>();
		}
		
		
		
		for(StationNotes scheduleJob : scheduleJobList){
			CronTrigger cronTrigger = StationNotesUtils.getCronTrigger(scheduler, scheduleJob.getId_());
            //如果不存在，则创建
            if(cronTrigger == null) {
                StationNotesUtils.createScheduleJob(scheduler, scheduleJob);
            }else {
                StationNotesUtils.updateScheduleJob(scheduler, scheduleJob);
            }
		}
	}
	
	public StationNotes queryObject(Long jobId) {
		return (StationNotes) this.findBySqlUniqueObject("select * from "+tableName(StationNotes.class)+"  where id_="+jobId+"", StationNotes.class, null);
	}

	public List<StationNotes> queryList(Map<String, Object> map) {
		String sql="select * from "+tableName(StationNotes.class)+" where 1=1 ";
		String join=getJoinSql();
        if(!ChkUtil.isEmpty(join)) sql+=" and deptId in("+join+")";
          Object bedNO=map.get("bedNO");
		if(!ChkUtil.isEmptyAllObject(bedNO)){
			if (bedNO.toString().contains("%") || bedNO.toString().contains("_")) {
				bedNO = bedNO.toString().trim().replace("%", "\\%").replace("_", "\\_");
				bedNO = "%" + bedNO + "%";
				sql += " and bedNO like #{pojo.bedNO} escape '\\'";
				map.put("bedNO", "%" + bedNO.toString().trim() + "%");
			} else {
				bedNO = "%" + bedNO.toString().trim() + "%";
				sql += " and bedNO like #{pojo.bedNO} ";
				map.put("bedNO", "%" + bedNO.toString().trim() + "%");
			}
		}
		
		if(!ChkUtil.isEmptyAllObject(map.get("offset"))&&!ChkUtil.isEmptyAllObject(map.get("limit"))){
//			map.put("beanName", beanName);
			sql+=" limit #{pojo.offset},#{pojo.limit} ";
		}
		return  this.findBySql(sql, StationNotes.class, map);
	}

	public int queryTotal(Map<String, Object> map) {
		String sql="select count(1) count from "+tableName(StationNotes.class)+" where 1=1 ";
		String join=getJoinSql();
        if(!ChkUtil.isEmpty(join)) sql+=" and deptId in("+join+")";
		Object bedNO=map.get("bedNO");
		Map params=new HashMap();
		if(!ChkUtil.isEmptyAllObject(bedNO)) {
			bedNO = "%" + bedNO.toString().trim()+ "%";
			map.put("bedNO", bedNO);
			sql+=" and bedNO=#{pojo.bedNO} ";
		}
		int count=0;
		Map m=(Map) findBySqlUniqueObject(sql, Map.class, map);
		if(!ChkUtil.isEmptyAllObject(m)) count=Integer.parseInt(m.get("count").toString());
		return count;
	}

	@Transactional
	public void save(StationNotes scheduleJob) {
		scheduleJob.setCreateTime(new Date());
		scheduleJob.setStatus(ScheduleStatus.NORMAL.getValue());
         int count=getBaseMapperCRUD().insert(scheduleJob);
        StationNotesUtils.createScheduleJob(scheduler, scheduleJob);
    }
	
	@Transactional
	public void update(StationNotes scheduleJob) {
        StationNotesUtils.updateScheduleJob(scheduler, scheduleJob);
        StationNotes scheduleJobOld=(StationNotes) findBySqlUniqueObject("select * from  "+tableName(StationNotes.class)+" where id_="+scheduleJob.getId_()+"", StationNotes.class, null);
        try {
        	if(!ChkUtil.isEmpty(scheduleJobOld)){
        		BeanUtils.copyProperties(scheduleJobOld, scheduleJob);
        		updateObject(scheduleJobOld);
        	}
		} catch (IllegalAccessException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

	@Transactional
    public void deleteBatch(Long[] jobIds) {
		String  jobs="";
    	for(Long jobId : jobIds){
    		jobs+=jobId+",";
    		StationNotesUtils.deleteScheduleJob(scheduler, jobId);
    	}
    	if(!ChkUtil.isEmpty(jobs)) {
    		jobs=jobs.substring(0, jobs.length()-1);
    		//删除数据
    		String sql="delete from "+tableName(StationNotes.class)+"  where id_ in("+jobs+")";
    		executeSql(sql, null);
    	}
	}

	
    public int updateBatch(Long[] jobIds, int status){
    	Map<String, Object> map = new HashMap<>();
    	String  jobs="";
    	for(Long jobId : jobIds){
    		jobs+=jobId+",";
    	}
    	int count=0;
    	if(!ChkUtil.isEmpty(jobs)) {
    		jobs=jobs.substring(0, jobs.length()-1);
    		String sql="update "+tableName(StationNotes.class)+" set status = "+status+" where id_  in("+jobs+")";
    		count= executeSql(sql, null);
    	}
    	 
    	return count;
    }
    
	@Transactional
    public void run(Long[] jobIds) {
    	for(Long jobId : jobIds){
    		StationNotesUtils.run(scheduler, queryObject(jobId));
    	}
    }

	@Transactional
    public void pause(Long[] jobIds) {
        for(Long jobId : jobIds){
    		StationNotesUtils.pauseJob(scheduler, jobId);
    	}
        
    	updateBatch(jobIds, ScheduleStatus.PAUSE.getValue());
    }

	@Transactional
    public void resume(Long[] jobIds) {
    	for(Long jobId : jobIds){
    		StationNotesUtils.resumeJob(scheduler, jobId);
    	}
    	updateBatch(jobIds, ScheduleStatus.NORMAL.getValue());
    }
	
	public String getJoinSql(){
		SysUserEntity user= (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
		String join="";
		//如果不是超级管理员，则只能查询本组织及子组织数据
//		 join=sysDeptService.getSubDeptIdList(user.getDeptId());
		if(user.getUserId() != Constant.SUPER_ADMIN){
			 join=sysDeptService.getSubDeptIdList(user.getDeptId());
		}
		return join;
	}

	/**
	 * @return
	 */
	public List queryBedNOList(Long deptId,Long sickAreaNO) {
		Map<String, Object> map=new HashMap();
		String sql="select bedNO text,bedNO value from "+tableName(ProductDeviceInit.class)+" where 1=1 ";
		String join=getJoinSql();
        if(!ChkUtil.isEmpty(join)) sql+=" and deptId in("+join+")";
        
    	if(!ChkUtil.isEmptyAllObject(sickAreaNO)&&!ChkUtil.isEmpty(deptId)){
			map.put("deptId", deptId);
			map.put("sickAreaNO", sickAreaNO);
			sql+=" and sickAreaNO=#{pojo.sickAreaNO} and deptId=#{pojo.deptId} and deviceUseType=3";
		}else {
			return new ArrayList();
		}
    	List l=this.findBySql(sql, null, map);
		return l;
	}
	
}
